package com.darkevil.jdspider

import com.darkevil.jdspider.service.CategoryService
import com.darkevil.jdspider.service.QueueService
import org.apache.ibatis.mapping.DatabaseIdProvider
import org.apache.ibatis.mapping.VendorDatabaseIdProvider
import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.core.task.AsyncTaskExecutor
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import org.springframework.transaction.annotation.EnableTransactionManagement
import java.util.*


@SpringBootApplication
@EnableAsync
//@EnableScheduling
@MapperScan("com.darkevil.jdspider.mapper")
@EnableTransactionManagement
class JdSpiderApplication {
    /**
     * 自定义异步线程池
     * @return
     */
    @Bean
    fun taskExecutor(): AsyncTaskExecutor {
        val executor = ThreadPoolTaskExecutor()
        executor.corePoolSize = 60 
        executor.maxPoolSize = 200
        executor.keepAliveSeconds=5
        executor.setThreadNamePrefix("Task-Executor-")

        // 设置拒绝策略
//        executor.setRejectedExecutionHandler { r, executor ->
//            // .....
//        }
        // 使用预定义的异常处理类
        // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        return executor
    }

    /**
     * 自动识别使用的数据库类型
     * 在mapper.xml中databaseId的值就是跟这里对应，
     * 如果没有databaseId选择则说明该sql适用所有数据库
     * */
    @Bean
    fun getDatabaseIdProvider(): DatabaseIdProvider {
        val databaseIdProvider = VendorDatabaseIdProvider()
        val properties = Properties()
        properties.setProperty("Oracle", "oracle")
        properties.setProperty("MySQL", "mysql")
        properties.setProperty("DB2", "db2")
        properties.setProperty("Derby", "derby")
        properties.setProperty("H2", "h2")
        properties.setProperty("HSQL", "hsql")
        properties.setProperty("Informix", "informix")
        properties.setProperty("MS-SQL", "ms-sql")
        properties.setProperty("PostgreSQL", "postgresql")
        properties.setProperty("Sybase", "sybase")
        properties.setProperty("Hana", "hana")
        databaseIdProvider.setProperties(properties)
        return databaseIdProvider
    }
}




fun main(args: Array<String>) {
    val context = runApplication<JdSpiderApplication>(*args)
    val queueService=context.getBean(QueueService::class.java)
    queueService.productQueueSave()
    val jdSpiderService = context.getBean(CategoryService::class.java)
    jdSpiderService.getCategory()
}
